<template>
	<div v-if="list.data">
		<ul>
			<li v-for="model in list.data"><item-component v-bind:model="model"></item-component></li>
		</ul>
		<div class="list load-more">
			<a href="javascript:void(0);" v-on:click="load" id="btn-load-more">加载更多</a>
		</div>
	</div>
	<div v-if="!list.data" class="list no-data" id="message-show" v-bind:message="message">
		{{ message }}
	</div>
</template>

<script>

	const $ = require('jquery');

	const Vue = require('vue');	

	var data = {
		message: '暂无数据',
		list: [],
		page: 1,
		is_loading: false
	};

	var load = ($this, is_new) => {

		data.message = '加载中...';

		if(!data.is_loading){

			$('#btn-load-more').html('加载中...');

			data.is_loading = true;
			//获取数据
			$this.$http.get('/news/' + data.page).then((response) => {

				var respData = response.data.retData;

				if(is_new){

					data.list = respData;

				}else{

					if(respData 
						&& respData.return_count > 0){
						for(var i = 0, length = respData.data.length; i < length; i++){
							data.list.data.push(respData.data[i]);
						}
					}
					
				}

				$('#btn-load-more').html('加载更多');

				if(respData){
					if(respData.has_more === 1 && respData.return_count > 0){
						data.page += 1;
					}
					if(respData.has_more === 0){
						$('#btn-load-more').html('没有更多内容了');
					}
				}

				data.is_loading = false;

			}, (response) => {
				//error
				console.log(response);

				data.is_loading = false;

				$('#btn-load-more').html('加载更多');

			});
		}
	}

	//注册并实例化组件
	var itemComponent = Vue.extend({
		props: ['model'],
		template: '<div><a href="{{ model.url }}" target="_blank"><img v-bind:src="model.img_url" alt="{{ model.title }}" /><div><h4 class="item-title">{{ model.title }}</h4><span>{{ model.datetime }}</span><p>{{ model.abstract }}...</p></a></div></div>'
	});

	export default {
		components: { 
			'item-component': itemComponent
		},
		data(){
			return new Vue({
				data: data
			})
		},
		ready(){
			console.log('ready');
		},
		attached(){
			console.log('attached');
		},
		route: {
			data ({ to }) {

				//每次进入页面 从新加载
				data.list = [];
				data.page = 1;
				console.log('route list');
				// console.log(to);

				load(this, true);
				
			}
		},
		methods: {
			load(){
				load(this, false);
			}
		}
	}
</script>